using System;
using System.Data;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using Microsoft.Win32;
using System.IO;
using TIMA.DevTeam;

namespace TIMA
{
    public partial class Login : XPopupForm
    {
        public Login()
        {
            InitializeComponent();
        }

        private void Login_Load(object sender, EventArgs e)
        {
            this.AcceptButton = btnLogin;
            this.KeyPreview = true;
            this.Shown += new EventHandler(Login_Shown);
            this.KeyDown += new KeyEventHandler(Login_KeyDown);

            if (Environment.MachineName.ToUpper() == "KGULCAN")
            {
                //txtUsername.Text = "kasim.gulcan";
                //txtPassword.Text = "//**--";
                //btnLogin.PerformClick();
            }
        }

        private void Login_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.F12)
            {
                XtraMessageBox.Show("OK");
            }
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (CheckCredentials(txtUsername.Text, txtPassword.Text))
            {
                if (lblNewPassword.Visible)
                {
                    if (txtNewPassword.Text == "")
                    {
                        XtraMessageBox.Show("New password cannot be blank.");
                        return;
                    }
                    else if (txtNewPassword.Text.Length < 3)
                    {
                        XtraMessageBox.Show("New password must be at least 3 characters long.");
                        return;
                    }

                    Data.DM.ExecuteScalar("UpdKullanici", txtUsername.Text, txtNewPassword.Text);
                }

                this.DialogResult = DialogResult.OK;
            }
            else
            {
                XtraMessageBox.Show("Access denied!");
                txtPassword.Text = String.Empty;
                txtPassword.Focus();
            }
        }

        private void Login_Shown(object sender, EventArgs e)
        {
            if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
                this.Text += " - v" + System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();

            string userName = RememberUser();

            if (userName != String.Empty)
            {
                txtUsername.Text = userName;
                txtPassword.Focus();
            }
            else
                txtUsername.Focus();
        }

        private string RememberUser(string UserNameToSave = "")
        {
            try
            {
                RegistryKey register = Registry.CurrentUser.CreateSubKey(@"Software\TIMA");
                if (UserNameToSave != "")
                {
                    register.SetValue("UserLastLoggedIn", UserNameToSave, RegistryValueKind.String);
                    Registry.LocalMachine.Flush();
                }
                else
                    UserNameToSave = (string)register.GetValue("UserLastLoggedIn", String.Empty);

            }
            catch (Exception)
            {
            }
            return UserNameToSave;
        }

        private void lnkChangePassword_OpenLink(object sender, OpenLinkEventArgs e)
        {
            bool visible = (btnChangePassword.Text == "Change Password");

            btnChangePassword.Text = visible ? "Don't Change Password" : "Change Password";

            lblNewPassword.Visible = txtNewPassword.Visible = visible;
        }

        public bool CheckCredentials(string Username, string Password)
        {
            DataTable dtCredentials = null;
            AppSession.UserInfo = new User();
            AppSession.UserInfo.UserName = Username;
            AppSession.UserInfo.Password = Password; ;
             
            TIMA.ceGate.ceGateSoapClient gate = new TIMA.ceGate.ceGateSoapClient();

            try
            {
                dtCredentials = gate.GetTIMACredentials(Username, Password, "confexpert.karbel.com");
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("Cannot access to the gate service! Please check the internet connection.");
                Clipboard.SetText(ex.ToString());
                return false;
            }

            if (dtCredentials == null)
                return false;

            string connectionString = dtCredentials.Rows[0]["ConnectionString"].ToString();
            Data.Init(connectionString);


            DataRow drUser = dtCredentials.Rows[0];

            AppSession.UserInfo.UserId = (int)drUser["KullaniciId"];
            AppSession.UserInfo.Name = drUser["AdSoyad"].ToString();
            AppSession.UserInfo.Email = drUser["ePosta"].ToString();

            RememberUser(Username);

            return true;
        }

        private void cmbFuar_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnChangePassword.Text = "Change Password";
            lblNewPassword.Visible = txtNewPassword.Visible = false;          
        }
    }
}